﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RealtyManagementSystem.BLL;
using RealtyManagementSystem.DAL;

namespace RealtyManagementSystem.Web.Admin
{
    /// <summary>
    ///
    /// </summary>
    public partial class UserRoleManagement : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindAllRoles();
                Guid roleID = new Guid(ddlRoles.SelectedValue);

                BindGvUsersInRole(roleID);
            }
        }

        private void BindAllRoles()
        {
            List<aspnet_Roles> allRoles = new Role().GetAllRoles();

            this.ddlRoles.DataSource = allRoles;
            this.ddlRoles.DataTextField = "Description";
            this.ddlRoles.DataValueField = "RoleId";
            this.ddlRoles.DataBind();
        }

        protected void dddlRoles_SelectedIndexChanged(object sender, EventArgs e)
        {
            Guid roleID = new Guid(ddlRoles.SelectedValue);

            BindGvUsersInRole(roleID);

            if (ddlRoles.SelectedIndex == 2)//realty
            {
                this.divAddRManager.Visible = true;
                hLinkAddUser.Text = "添加新物业管理员";
                hLinkAddUser.NavigateUrl = "CreateNewUser.aspx?userType=2";
            }
            else if (ddlRoles.SelectedIndex == 1)//householder user
            {
                this.divAddRManager.Visible = false;
                // do nothing
            }
            else if (ddlRoles.SelectedIndex == 0)//super user
            {
                this.divAddRManager.Visible = true;
                hLinkAddUser.Text = "添加新超级管理员";
                hLinkAddUser.NavigateUrl = "CreateNewUser.aspx?userType=0";
            }
            else
            {
                throw new ArgumentOutOfRangeException();
            }
        }

        private void BindGvUsersInRole(Guid roleID)
        {
            using (var dataContext = new realtydbEntities())
            {
                List<aspnet_Users> users = (
                   from rol in dataContext.aspnet_Roles.Include("aspnet_Users.aspnet_Membership")
                   from usr in rol.aspnet_Users
                   where rol.RoleId == roleID
                   select usr
                    ).Take(200).ToList();

                this.gvUsersInRole.DataSource = users;
                this.gvUsersInRole.DataBind();
            }
        }
    }//end class
}